﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.Globalization;
using sdamarketing.App_Code;


namespace sdamarketing.Forum
{
    public partial class reply : BasePage
    {


        //reply CustomIncludes begin
        protected CCUtility Utility;

        protected string original_sSQL;
        protected string original_sCountSQL;
        protected int original_CountPage;

        protected int i_original_curpage = 1;

        protected string reply_FormAction = "index.aspx?";
        protected string original_FormAction = ".aspx?";

        public reply()
        {
            this.Init += new System.EventHandler(Page_Init);
        }

        public void ValidateNumeric(object source, ServerValidateEventArgs args)
        {
            try
            {
                Decimal temp = Decimal.Parse(args.Value);
                args.IsValid = true;
            }
            catch
            {
                args.IsValid = false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Utility = new CCUtility(this);

            if (!IsPostBack)
            {
                reply_author.Text = Session["username"].ToString();
                p_reply_message_id.Value = Utility.GetParam("message_id"); Page_Show(sender, e);
            }
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP+ Windows Form Designer.
            //
            if (Utility != null) Utility.DBClose();
        }

        protected void Page_Init(object sender, EventArgs e)
        {

            InitializeComponent();
        }

        /// <summary>
        ///    Required method for Designer support - do not modify
        ///    the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }


        protected void Page_Show(object sender, EventArgs e)
        {
            reply_Show();
            original_Bind();

        }

        private bool reply_Validate()
        {
            bool result = true;
            reply_ValidationSummary.Text = "";

            for (int i = 0; i < Page.Validators.Count; i++)
            {
                if (((System.Web.UI.WebControls.BaseValidator)Page.Validators[i]).ID.ToString().StartsWith("reply"))
                {
                    if (!Page.Validators[i].IsValid)
                    {
                        reply_ValidationSummary.Text += Page.Validators[i].ErrorMessage + "<br>";
                        result = false;
                    }
                }
            }

            reply_ValidationSummary.Visible = (!result);
            return result;
        }

        void reply_Show()
        {

            bool ActionInsert = true;

            if (p_reply_message_id.Value.Length > 0)
            {
                string sWhere = "";

                sWhere += "message_id=" + CCUtility.ToSQL(p_reply_message_id.Value, FieldTypes.Number);

                // reply Open Event begin
                // reply Open Event end
                string sSQL = "select * from messages where " + sWhere;
                SqlDataAdapter dsCommand = new SqlDataAdapter(sSQL, Utility.Connection);
                DataSet ds = new DataSet();
                DataRow row;

                if (dsCommand.Fill(ds, 0, 1, "reply") > 0)
                {
                    row = ds.Tables[0].Rows[0];

                    reply_message_id.Value = CCUtility.GetValue(row, "message_id");


                    reply_smiley_id.Value = CCUtility.GetValue(row, "smiley_id");

                    reply_topic.Text = CCUtility.GetValue(row, "topic");
                    reply_author.Text = CCUtility.GetValue(row, "author");
                    reply_message.Text = CCUtility.GetValue(row, "message");
                    reply_date_entered.Value = CCUtility.GetValue(row, "date_entered").Replace('T', ' ');
                    reply_last_modified.Value = CCUtility.GetValue(row, "last_modified").Replace('T', ' ');
                    reply_mid.Value = CCUtility.GetValue(row, "message_parent_id");

                    //reply_insert.Visible = false;
                    ActionInsert = false;
                }
            }

            if (ActionInsert)
            {

                String pValue;

                pValue = Utility.GetParam("mid"); reply_mid.Value = pValue;
                // reply ShowInsert Event begin
                reply_date_entered.Value = DateTime.Now.ToString("g");
                reply_last_modified.Value = DateTime.Now.ToString("g");
                reply_smiley_id.Value = "";

                reply_smileys.Text = "<input type=\"radio\" name=\"smiley_id\" value=\"0\" checked>none&nbsp;";
                SqlCommand command = new SqlCommand("SELECT * FROM smileys", Utility.Connection);
                SqlDataReader reader = command.ExecuteReader();
                int i = 0;
                while (reader.Read())
                {
                    if (i == 5)
                    {
                        reply_smileys.Text += "<input type=\"radio\" name=\"smiley_id\" value=\"" +
                        reader["smiley_id"].ToString() + "\"><img src=\"" +
                        reader["smiley_url"].ToString() + "\" title=\"" +
                        reader["smiley_name"].ToString() + "\"><br/>";
                    }
                    else
                    {
                        reply_smileys.Text += "<input type=\"radio\" name=\"smiley_id\" value=\"" +
                        reader["smiley_id"].ToString() + "\"><img src=\"" +
                        reader["smiley_url"].ToString() + "\" title=\"" +
                        reader["smiley_name"].ToString() + "\">&nbsp;";
                    }
                    i++;
                }
                reader.Close();
            }
        }

        void reply_BeforeSQLExecute(string SQL, String Action)
        {
        }

        const int original_PAGENUM = 20;

        public void original_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {

            // original Show Event begin
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ((Label)e.Item.FindControl("original_message")).Text = ((DataRowView)e.Item.DataItem)["m_message"].ToString().Replace("\r\n", "<br>");
            }
            // original Show Event end
        }


        ICollection original_CreateDataSource()
        {
            original_sSQL = "";
            original_sCountSQL = "";
            string sWhere = "", sOrder = "";
            bool HasParam = false;

            System.Collections.Specialized.StringDictionary Params = new System.Collections.Specialized.StringDictionary();


            if (!Params.ContainsKey("mid"))
            {
                string temp = Utility.GetParam("mid");
                if (Utility.IsNumeric(null, temp) && temp.Length > 0) { temp = CCUtility.ToSQL(temp, FieldTypes.Number); } else { temp = ""; }
                Params.Add("mid", temp);
            }

            if (Params["mid"].Length > 0)
            {
                HasParam = true;
                sWhere += "m.[message_id]=" + Params["mid"];
            }


            if (HasParam)
                sWhere = " WHERE (" + sWhere + ")";

            original_sSQL = "select [m].[author] as m_author, " +
            "[m].[date_entered] as m_date_entered, " +
            "[m].[message] as m_message, " +
            "[m].[message_id] as m_message_id, " +
            "[m].[topic] as m_topic " +
            " from [messages] m ";

            original_sSQL = original_sSQL + sWhere + sOrder;

            SqlDataAdapter command = new SqlDataAdapter(original_sSQL, Utility.Connection);
            DataSet ds = new DataSet();

            command.Fill(ds, 0, original_PAGENUM, "original");
            DataView Source;
            Source = new DataView(ds.Tables[0]);

            if (ds.Tables[0].Rows.Count == 0)
            {
                original_no_records.Visible = true;
            }
            else
            {
                original_no_records.Visible = false;
            }

            return Source;

        }


        void original_Bind()
        {
            original_Repeater.DataSource = original_CreateDataSource();
            original_Repeater.DataBind();
        }

        protected void reply_button_Click(object sender, EventArgs e)
        {
            string sSQL = "";
            bool bResult = reply_Validate();

            string p2_smiley_id = CCUtility.ToSQL(Utility.GetParam("reply_smiley_id"), FieldTypes.Number);
            string p2_topic = CCUtility.ToSQL(Utility.GetParam("reply_topic"), FieldTypes.Text);
            string p2_author = CCUtility.ToSQL(Utility.GetParam("reply_author"), FieldTypes.Text);
            string p2_message = CCUtility.ToSQL(Utility.GetParam("reply_message"), FieldTypes.Memo);
            string p2_date_entered = CCUtility.ToSQL(Utility.GetParam("reply_date_entered"), FieldTypes.Date);
            string p2_last_modified = CCUtility.ToSQL(Utility.GetParam("reply_last_modified"), FieldTypes.Date);
            string p2_mid = CCUtility.ToSQL(Utility.GetParam("reply_mid"), FieldTypes.Number);
            // reply Insert Event begin
            CultureInfo ci = new CultureInfo("en-us");

            string datumVreme = System.DateTime.Now.ToString("u", ci).Replace("Z", "");
            string sqlot = "UPDATE messages SET last_modified='" + datumVreme + "' WHERE message_id=" + reply_mid.Value;
            Utility.Execute("UPDATE messages SET last_modified='" + datumVreme + "' WHERE message_id=" + reply_mid.Value);
            p2_smiley_id = CCUtility.ToSQL(Utility.GetParam("smiley_id"), FieldTypes.Number);

            if (bResult)
            {

                if (sSQL.Length == 0)
                {
                    sSQL = "insert into messages (" +
                        "smiley_id," +
                        "topic," +
                        "author," +
                        "message," +
                        "date_entered," +
                        "last_modified," +
                        "message_parent_id)" +
                        " values (" +
                        p2_smiley_id + ",'" +
                        reply_topic.Text + "','" +
                        reply_author.Text + "','" +
                        reply_message.Text + "'," +
                        "'" + datumVreme + "'" + "," +
                        "'" + datumVreme + "'" + "," +
                        reply_mid.Value + ")";
                }
                reply_BeforeSQLExecute(sSQL, "Insert");
                SqlCommand cmd = new SqlCommand(sSQL, Utility.Connection);

                cmd.ExecuteNonQuery();

                //Snimanje na TEKSTOT od Postot na Forumot vo PodatociZaAnaliza
                SqlConnection connection = ConnectionMenager.GetConnection();
                String sql = "INSERT INTO PodatociZaAnaliza (idUser,textZaAnaliza) VALUES ('" + Session["idUser"].ToString() + "' , '" + reply_message.Text + "')";
                SqlCommand command = new SqlCommand(sql, connection);
                command.ExecuteNonQuery();
                connection.Close();

                Response.Redirect(reply_FormAction + "mid=" + Server.UrlEncode(Utility.GetParam("mid")) + "&");
            }

        }
    }
}
